<?php
class User_model extends CI_Model {
	var $uid = '';
	var $nickname = '';
	var $birthday = '';
	var $workplace = '';
	var $graschool = '';
	
	function get_uid() {
		return $this->uid;
	}

	function set_uid( $uid ) {
		$this->uid = $uid;
		// $this->Column_model->speak(); // 可以调用其他model的函数
	}
	
	function clear_uid() {
		$this->uid = "";
	}
	
	function is_empty_uid() {
		return empty( $this->uid );
	}
	
	function feed_list() {	// 获取订阅的信息
		if( empty( $this->uid ) ) {	// 如果uid为空
			return "<p>UID为空</p>";
		} else {
			return "<p>uid = {$this->uid} </p>";
		}
	}
	
	function user_statis( $uid=-1, $type = 0 ) {
		// 获取用户的统计信息，根据$type
		// $type 
		// 0=专栏 1=作者 2=故事 3=读者
		$data['error'] = 0;
		$data['type'] = $type;
		$data['num' ] = 0;
		
		if( $uid == -1 ) {
			$uid = $this->uid;
		}
		
		$sql = "";
		switch( $type ) {
			case 0:
				$sql = "
					SELECT COUNT(*) AS num
					FROM follow_topic
					WHERE	 user_id = '{$uid}'
				";
				break;
			case 1:
				$sql = "
					SELECT COUNT(*) AS num
					FROM follow_user
					WHERE	 user_id = '{$uid}'
				";
				break;
			case 2:
				$sql = "
					SELECT COUNT(*) AS num
					FROM story
					WHERE	user_id = '{$uid}'
					AND story_type = '0'
				";
				break;
			case 3: 
				$sql = "
					SELECT	COUNT(*) AS num
					FROM	follow_user
					WHERE follow_target_id = '{$uid}'
				";
				break;
		}
		
		if( empty( $sql ) ) {
			$data['error'] = 2;
			return $data;
		}
		$query = $this->db->query( $sql );
		$data['num'] = $query->row()->num;
		
		return $data;
	}
	
	function following_cat( $type=0 ) {	
		// 获取关注的专栏或作者
		// type 0=专栏 1=作者
		$data['error'] = 0;
		$data['list'] = array();
		if( $this->is_empty_uid()  ) {
			$data['error'] = 1;	// 没有uid，无法查询
			return $data;
		}
		
		$sql = "";
		if( $type == 0 ) {
			$sql = "
				SELECT topic_id AS id
				FROM follow_topic
				WHERE user_id = {$this->uid}
				ORDER BY id ASC
				
			";
		} else if ( $type == 1 ) {
			$sql = "
				SELECT follow_target_id AS id
				FROM follow_user
				WHERE user_id = {$this->uid}
				ORDER BY id ASC
			";
		}
		
		if( empty( $sql ) ) {
			$data['error'] = 2;	// sql语句为空
			return $data;
		}
		
		$query = $this->db->query( $sql );
		foreach( $query->result_array() as $row ) {	
			$data['list'] []= $row['id'];
		}
		
		return $data;
	}
	
	function num_feed_stories( $type=0, $min_date=0 ) {
		// 获取订阅的专栏或作者发布的故事数
		// type 0 = 专栏 1=作者
		$data['error'] = 0;
		$data['num'] = 0;
		$following = $this->following_cat( $type );
		if( $following['error'] != 0 ) {
			$data['error'] = $following['error'];
			return $data;
		}
		
		if( count( $following['list'] ) == 0 ) {
			$data['error'] = 3;
			return $data;
		}
		
		$cats = array();	// 目录
		
		$sql = "";
		$serial_list = '('.implode( ',', $following['list'] ).')';
		 
		 if( $type == 0 ) {
			$sql = "
				SELECT COUNT(*) AS num
				FROM story 
				WHERE topic_id IN {$serial_list} 
					AND post_date >= '{$min_date}'
					AND story_type = '0'
			";
		 } else {
			$sql = "
				SELECT COUNT(*) AS num
				FROM story 
				WHERE user_id IN {$serial_list} 
					AND post_date >= '{$min_date}'
					AND story_type = '0'
			";
		 }

		if( empty( $sql ) ) {
			$data['error'] = 2;
			return $data;
		}
		
		$query = $this->db->query( $sql );
		$data['num'] = $query->row()->num;
		return $data;
	}
	
	function arr_cat_story_ids( $list, $type = 0, $min_date = 0 ) {
		// 获取最近产生的布丁索引
		// $list 关注的厨师或者店铺的ID列表
		// $type = 0 按照店铺 
		// $type = 1 按照厨师
		
		$data['error'] = 0;
		$data['list'] = array();
		
		$sql = "";
		if( count( $list ) == 0 ) {
			$data['error'] = 3;	// 为空
			return $data;
		}
		$serial_list = '('.implode( ',', $list ).')';
		
		if( $type == 0 ) {
			$sql = "
				SELECT story_id, post_date
				FROM story 
				WHERE topic_id IN {$serial_list} 
					AND post_date > '{$min_date}'
					AND story_type = '0'
				ORDER BY post_date ASC
			";
		} else if( $type == 1 ) {
			$sql = "
				SELECT story_id, post_date
				FROM story 
				WHERE user_id IN {$serial_list}
					AND story_type = '0'
				ORDER BY post_date ASC
			";
		}
		
		if( empty( $sql ) ) {
			$data['error'] = 2;
			return $data;
		}
		
		$query = $this->db->query( $sql );
		$data['list'] = $query->result_array();
	
		return $data;
	}
	
	function insert_one_feed( $type, $data ) {
		// 插入一条更新布丁信息
		// in: $user_id 用户id
		// in: $type 
		// in: $feed 布丁信息摘要
		if( $this->is_empty_uid() ) return 1;
		
		extract( $data );
		
		$a['story_id'] = $story_id;
		$a['user_id'] = $this->uid;
		$a['type'] = $type;
		
		$b = $this->db->where( $a )
			->from('feeds')
			->count_all_results();	
			
		if( $b == 0 ) {
			$a['post_date'] = $post_date;
			$this->db->insert( 'feeds', $a );
		}
		
		return 0;
	}
	
	function update_feed_table( $type = 0, $min_date = 0 ) {
		// 将更新的布丁信息写入feeds表中
		// $user_id 用户id
		// $type 用户类型
		// $min_date 操作$min_date之后产生的布丁
		$error = 0;
		if( $this->is_empty_uid() )  return 1; 	// uid为空
		$a = $this->following_cat( $type );
		extract( $a );
		if( $error != 0 ) {
			return  $error;
		}
		
		// print_arr( $a );	// tbd
		
		if( count( $list ) > 0 ) {	// 有关注的话题
			$b = $this->arr_cat_story_ids( $list, $type, $min_date );
			extract( $b );
			if( $error != 0 ) return $error;
			foreach( $list as $item ) {
				// print_arr( $item );	// tbd
				if( $this->insert_one_feed( $type, $item ) )
					return 4;	// 插入失败
			}
		} else {
				return 3;	// 没有关注的话题或作者
		}
		
		return $error;
	}
	
	function fetch_feed_stories( $type=0, $start=0, $size=1000 ) {
		// 从feeds表获取更新的布丁信息
		// return 布丁信息数组
		// limit $start, $size
		$data['error'] = 0;
		$data['list'] = array();
		if( $this->is_empty_uid() ) {
			$data['error'] = 1;	// uid为空
			return $data;
		}
		
		$sql = "";
		if( $type == 0 ) {
			$sql = "
				SELECT 
					topic.topic_id AS cat_id,
					topic.topic_title AS cat_name,
					topic.topic_icon AS img,
					user.user_id,
					user.user_nickname,
					story.story_id,
					story.story_title,
					story.story_content,
					story.post_date
				FROM story,feeds,topic,user
				WHERE feeds.user_id = '{$this->uid}' 
				  AND feeds.type='{$type}' 
				  AND story.story_id=feeds.story_id 
				  AND story.topic_id=topic.topic_id
				  AND story.user_id = user.user_id
				  AND story.story_type = '0'
				ORDER BY story.post_date DESC
				LIMIT {$start}, {$size}
			";
		} else if( $type == 1 ) {
				$sql = "
				SELECT 
					user.user_id AS cat_id,
					user.user_nickname AS cat_name,
					topic.topic_id,
					topic.topic_title,
					user.user_photo AS img,
					story.story_id,
					story.story_title,
					story.story_content,
					story.post_date
				FROM story,feeds,topic,user
				WHERE feeds.user_id = '{$this->uid}' 
				  AND feeds.type='{$type}' 
				  AND story.story_id=feeds.story_id 
				  AND story.topic_id=topic.topic_id
				  AND story.user_id = user.user_id
				  AND story.story_type = '0'
				ORDER BY story.post_date DESC
				LIMIT {$start}, {$size}
			";
		}
		
		if( empty( $sql ) ) {
			$data['error'] = 2;	// sql为空
			return $data; 	
		}
		$query = $this->db->query( $sql );
		$data['list'] = $query->result_array(); 
		
		return $data;
	}
	
	function user_profile( $id='' ) {
		$data['error'] = 0;
		$data['row'] = array();
		
		if( empty( $id ) ) {
			$id = $this->uid;
		}
		
		$a['user_id'] = $id;
		$query = $this->db->where( $a )->get('user');
		$data['row'] = $query->row_array();
		return $data;
	}
	
	function follow_or_not( $type, $uid, $xid ) {
		// 查看用户是否关注了专栏或作者
		// type 0=专栏 1=作者
		if( $type == 0 ) {
			$sql = "
				SELECT COUNT(*) AS flag
				FROM	follow_topic
				WHERE topic_id = '{$xid}'
					AND user_id = '{$uid}'
			";
		} else if( $type == 1 ) {
			$sql ="
				SELECT COUNT(*) AS flag
				FROM 	follow_user
				WHERE user_id = '{$uid}'
					AND follow_target_id = '{$xid}'
			";
		}
		
		$query = $this->db->query( $sql );
		return $query->row()->flag;
	}
	
	function html_user_statis( $uid ) {
		// html化用户的统计信息
		// 0=专栏 1=作者 2=故事 3=读者
		$x= $this->user_statis( $uid, 0 );
		$s['0'] = $x['num'];
		
		$x = $this->user_statis( $uid, 1 );
		$s['1'] = $x['num'];
		
		$x = $this->user_statis( $uid, 2 );
		$s['2'] = $x['num'];
		
		$x = $this->user_statis( $uid, 3 );
		$s['3'] = $x['num'];
		
		$c_link = HOSTURL.'user/follow?type=0&id='.$uid;
		$a_link = HOSTURL.'user/follow?type=1&id='.$uid;
		$s_link = HOSTURL.'user/follow?type=2&id='.$uid;
		$r_link = HOSTURL.'user/follow?type=2&id='.$uid;
	
	?>
		<div class="user-stat nav nav-justified">
			<ul>
				<li><a href="<?=$c_link ?>"><strong><?=$s[0]?></strong><span>专栏</span></a></li>
				<li><a href="<?=$a_link ?>"><strong><?=$s[1]?></strong><span>作者</span></a></li>
				<li><a href="<?=$s_link ?>"><strong><?=$s[2]?></strong><span>故事</span></a></li>
				<li><a href="<?=$r_link ?>"><strong><?=$s[3]?></strong><span>读者</span></a></li>	
			</ul>
		</div>
	<?php
	}
	
	function html_user_profile( $user_info = array() ) {
		// 打印用户的详细资料
		// 
		extract( $user_info );
		$user = array();
		if( $gender != 0 ) {
			if ($gender == 1 ) {
				$gender = "男";
			} else if( $gender == 2 ){
				$gender = "女";
			}
			array_push( $user,  array( 'label'=>'性别', 'value'=> $gender ) );
		}
		
		$birthday = substr( $birthday, 0, 10 );
		if( !empty( $birthday ) && ($birthday !== "0000-00-00"))  {
			array_push( $user, array( 'label'=>'生日', 'value' => substr($birthday, 0, 10) ) );
		}
		
		if( !empty( $province ) || !empty( $city ) ) {
			$location = "{$province} {$city}";
			array_push( $user,  array( 'label'=>'所在地', 'value'=> $location ) );
		}
		
		array_push( $user, array( 'label'=>'注册时间', 'value'=> substr( $user_reg_date, 0, 16 ) ) );
		
		if( !empty( $workplace ) ) {
			array_push( $user,  array( 'label'=>'工作单位', 'value'=> $workplace ) );
		}
		
		if( !empty( $gra_school ) ) {
			array_push( $user,  array( 'label'=>'毕业学校', 'value'=> $gra_school ) );
		}
		
		echo "<div class='user-big-name'>";
		echo "<h3>{$user_nickname}</h3>";
		echo "<p>{$user_desc}</p>";
		echo "</div>";
		
		// begin print
		echo '<ul>';
		foreach( $user as $i ) {
			extract( $i );
			echo "<li><label>{$label}</label><span>{$value}</span></li>";
		}
		echo '</ul>';
	}
	
	function html_interact_with_user( $uid, $author_id ) {	// tbe
			// 根据$uid与$author_id的关系准备动作按钮
			// #uid 当前登录用户
			// #author_id 当前查看页面用户
			
			if( $uid == $author_id ) {
				$profile_link = HOSTURL.'user/editp?type=0'; 
				echo "<a href='".$profile_link."'>编辑个人资料</a>";
			} else {
				// 关注状态以及发送消息按钮
				$follow_or_not = $this->follow_or_not( 1, $uid, $author_id );
				// echo $follow_or_not;
				if( $follow_or_not == 0 ) {
					$status = "加关注";
					$cls = "";
				} else if( $follow_or_not == 1 ) {
					$status = "已关注";
					$cls = "followed";
				}
				$msg_link = HOSTURL.'user/write_msg?type=1&id='.$author_id;
			?>
			<ul>
				<?php
				if( $uid > 9999 ) { 
				?>
				<li class="<?=$cls?>"><a href="javascript:void(0);" rel="<?=$author_id?>" type="1" followed="<?=$follow_or_not?>" action="follow" id="change-user-follow-status"><?=$status?></a></li>
				<?php
				}
				?>
				<li><a href="<?=$msg_link?>" id="send-msg" target="_blank">写信</a></li>
			</ul>
			<?php
			}
		}
	
	function html_user_big_profile( $uid, $author_id) {	// tbe
		// 打印200个像素的用户头像
		// author_id 查看的作者编号
		// uid 当前登录的用户编号
		$u= $this->user_profile( $author_id );
		if( $u['error'] == 0 ) {
			$author = $u['row'];
		} else {
			echo '<p>查询错误</p>';
			return;
		}
		extract( $author );
		$user_photo = UVIEW_PATH.$user_photo;
?>
	<div class="user-big-profile-wrap">
		<div class="user-big-profile-box">
			
			<div class="user-big-photo">
				<img src="<?=$user_photo?>" width="200px" height="200px" class="img-rounded"/>
				<?php
					$this->html_user_statis( $author_id );
				?>
			</div>
			<div class="pull-left profile">
				<div class="user-all-profile">
					<?php
					$this->html_user_profile( $author );
					?>
				</div>
				
				<div class="user-action">
					<?php
					$this->html_interact_with_user( $uid, $author_id );
					?>
				</div>
			</div>
		</div>
	</div>
<?php
	}
	
	function get_recent_stories( $xid, $start, $size ) {
		// 获取作者最近发布的作品
		// author_id = 作者编号
		// num = 作品数量
		// 返回作品数组
		// type 0=专栏 1=作者
		$data['error'] = 0;
		$data['list'] = array();
		if( empty($xid) ) {
			$data['error'] = 1;
			return $data;
		}
			
		
		$sql = "
			SELECT 
				topic.topic_id AS cat_id,
				topic.topic_title AS cat_name,
				topic.topic_icon AS img,
				user.user_id,
				user.user_nickname,
				story.story_id,
				story.story_title,
				story.story_content,
				story.post_date,
				story.view_count
			FROM story,topic,user
			WHERE story.user_id = '{$xid}' 
			  AND story.topic_id=topic.topic_id
			  AND story.user_id = user.user_id
			  AND story.story_type = '0'
			ORDER BY story.post_date DESC
			LIMIT {$start}, {$size}
		";

	
		$query = $this->db->query( $sql );
		$data['list'] = $query->result_array();
		return $data;
	}
	
	function html_user_stories( $uid, $author_id, $start, $size) {
		// html最近发布的文章
		$r = $this->get_recent_stories( $author_id, $start, $size );
		if( $r['error'] == 0 ) {
			$sl = $r['list'];
		?>
		<script src="<?=base_url().'comm/js/user-action.js'?>"></script>
		<?php
		} else {
			echo '<p>查询错误</p>';
		}
		?>
			<div class='column-bdings-wrap' id='bding-feed-list'>
				<div class='column-bdings-box'>
			<?php
			if( count( $sl ) == 0 ) {
				echo "<p>尚未发布作品</p>";
			} else {
				foreach( $sl as $story ) {
					$this->Public_model->html_bding_item_column($uid, $story );
				}
			}
			?>
				</div>
			</div>
		<?php
	}
	
	
	function html_user_drafts( $page, $uid, $author_id) {
		// html最近发布的文章
		$data = $this->get_user_drafts( $page, $author_id );
		if( $r['error'] == 0 ) {
			$sl = $r['list'];
		?>
		<script src="<?=base_url().'comm/js/user-action.js'?>"></script>
		<?php
		} else {
			echo '<p>查询错误</p>';
		}
		?>
			<div class='column-bdings-wrap' id='bding-feed-list'>
				<div class='column-bdings-box'>
			<?php
			if( count( $sl ) == 0 ) {
				echo "<p>尚未发布作品</p>";
			} else {
				foreach( $sl as $story ) {
					$this->Public_model->html_bding_item_column($uid, $story );
				}
			}
			?>
				</div>
			</div>
		<?php
	}
	
	function html_user_stories_hoz( $uid, $author_id, $start, $size ) {
		// 列表显示
		$r = $this->get_recent_stories( $author_id, $start, $size );
		if( $r['error'] == 0 ) {
			$sl = $r['list'];
		?>
		<script src="<?=base_url().'comm/js/user-action.js'?>"></script>
		<?php
		} else {
			echo '<p>查询错误</p>';
		}
		?>
			<div class='column-bdings-wrap-hoz' id='bding-feed-list'>
				<div class='column-bdings-box-hoz'>
			<?php
			if( count( $sl ) == 0 ) {
				echo "<p>尚未发布作品</p>";
			} else {
				echo "<ul>";
				foreach( $sl as $story ) {
					$this->html_user_story_item_hoz($uid, $story );
				}
				echo "</ul>";
			}
			?>
				</div>
			</div>
		<?php
	}
	
	
	
	function get_follow_list( $type, $xid, $start, $size ) {
		// 获得关注列表
		// type 0=专栏 1=作者 2=粉丝
		switch( $type ) {
			case 0:
				$sql = "
					SELECT 
						follow_topic.topic_id AS id,
						topic.topic_icon AS img,
						topic.topic_title AS name
					FROM  topic, follow_topic
					WHERE follow_topic.user_id = '{$xid}'
						AND follow_topic.topic_id = topic.topic_id
					ORDER BY follow_topic.follow_date DESC
					LIMIT {$start}, {$size}
				";
				$cat = "专栏";
				break;
				
			case 1:
				$sql = "
					SELECT 
						follow_user.follow_target_id AS id,
						user.user_photo AS img,
						user.user_nickname AS name	
					FROM follow_user, user
					WHERE follow_user.user_id = '{$xid}'
						AND user.user_id = follow_user.follow_target_id
					ORDER BY follow_user.follow_date DESC
					LIMIT {$start}, {$size}
				";
				$cat = "作者";
				break;
				
			case 2:
				$sql = "
					SELECT 
						follow_user.user_id AS id,
						user.user_photo AS img,
						user.user_nickname AS name
					FROM	follow_user, user
					WHERE	follow_user.follow_target_id = '{$xid}'
						AND follow_user.user_id = user.user_id 
					ORDER BY follow_user.follow_date DESC
					LIMIT {$start}, {$size}
				";
				$cat = "读者";
				break;
		}
		
		$query = $this->db->query( $sql );
		$result['title'] = $cat;
		$result['list'] = $query->result_array();
		
		return $result;
	}
	
	function html_follow_list_short( $type, $author_id, $start, $size ) {
		$x = $this->user_statis($author_id, $type);
		$stories_num = $x['num'];
		$a = $this->get_follow_list( $type, $author_id, $start, $size );
		$title = $a['title'];
		$data = $a['list'];
		if( $type == 0 ) {
			$en_title = "columns";
		} else if( $type == 1 ) {
			$en_title = "authors";
		}
		$more_link = HOSTURL."user/follow?type={$type}&id={$author_id}";
		if( count( $data ) > 0 ) {
		?>
			<div class="attach-wrap">
				<div class="title"><span>关注<?=$title?><i style="color: #00664D">/ following <?=$en_title?></i></span></title></div>
				<div class="attach-box">
				<ul>
				<?php
					// print_arr( $data );
					foreach( $data as $item ) {
						extract( $item );
						if( $type == 0 ) {
							$cat_link = HOSTURL."column/?id=".$id;
							$cat_img = CVIEW_PATH.$img;
						} else if( $type == 1) {
							$cat_link = HOSTURL."user/?id=".$id;
							$cat_img = UVIEW_PATH.$img;
						}
				?>
						<li class="follow-item"><a href="<?=$cat_link?>" target="_blank" title="<?=$name?>" alt="<?=$name?>"><img src="<?=$cat_img?>" width="50px" height="50px" class="img-rounded"/></a></li>
				<?php
					}
				?>
				</ul>
				<?php
				if( $stories_num> $size ) {
				?>
				<p class="more"><a href="<?=$more_link?>">全部</a></p>
				<?php 
				}
				?>
				</div>
			</div>
		<?php
		}
	}
	
	function update_password( $data = array() ) {
		// 更新用户的密码
		extract( $data ) ;
		print_arr( $data );
		
		$old_pass = md5( mysql_real_escape_string( trim($old_pass) ) );
		if( $old_pass != $user_pass ) {
			// do something
			return false;
		} else {
			$new_pass = md5( mysql_real_escape_string( trim($new_pass) ) );
			$sql = "
				UPDATE user
				SET	user_pass = '{$recv_pwd}'
				WHERE user_id = '{$uid}'
			";
			return $this->db->query( $sql );
		}
	
	}
	
	function update_profile( $uid, $data = array() ) {
		// 更新用户的资料
		// print_arr( $data );	//tbd
		extract( $data );
		$birthday = $year.'-'.$month.'-'.$day;
		
		$nickname = mysql_real_escape_string( trim($nickname) );
		$gender = mysql_real_escape_string( $gender );
		$birthday = mysql_real_escape_string( $birthday );
		$province = mysql_real_escape_string( trim($province) );
		$city = mysql_real_escape_string( trim($city) );
		$workplace = mysql_real_escape_string( trim($workplace) );
		$gra_school = mysql_real_escape_string( trim($gra_school) );
		$intro = mysql_real_escape_string( trim($intro) );
		
		$sql = "
			UPDATE	user
			SET	
				user_nickname ='{$nickname}',
				gender = '{$gender}',
				birthday = '{$birthday}',
				province = '{$province}',
				city = '{$city}',
				workplace = '{$workplace}',
				gra_school = '{$gra_school}',
				user_desc = '{$intro}'
			WHERE user_id = '{$uid}'
		";
		if( $this->db->query( $sql ) ) {
			return true;
		}
		return false;
	}
	
	function get_read_history( $type , $uid, $start, $size ) { 
		// 获取阅读历史数据
		// type 0=今天 1=过去
		$str_date = date( 'Y-m-d ');
		$str_date .= " 00:00:00";
		$title = "今天";
		switch( $type ) {
			case 0:
				$sql = "SELECT story.story_id, story.story_title, story.user_id, history.record_date, topic.topic_id, topic.topic_title, user.user_nickname 
							FROM story, history, topic , user
							WHERE story.topic_id=topic.topic_id 
								AND story.story_id=history.story_id 
								AND story.user_id = user.user_id
								AND history.user_id='{$uid}' 
								AND record_date >= '{$str_date}'
							ORDER BY history.record_date DESC
							LIMIT {$start}, {$size}";
				break;
			case 1:
				$sql = "SELECT story.story_id, story.story_title, story.user_id, history.record_date, topic.topic_id, topic.topic_title, user.user_nickname  
							FROM story, history, topic, user 
							WHERE story.topic_id=topic.topic_id 
								AND story.story_id=history.story_id 
								AND story.user_id = user.user_id
								AND history.user_id='{$uid}' 
								AND record_date < '{$str_date}'
							ORDER BY history.record_date DESC
							LIMIT {$start}, {$size}";
				$title ="以往";
				break;
		}
		$query = $this->db->query( $sql );
		$result['day'] = $title;
		$result['list'] = $query->result_array();
	
		return $result;
	}
	
	function change_follow( $type, $action, $uid, $xid ) {
		// 改变关注的状态
		// type 0=专注 1=作者
		// action 0=添加关注 1=取消关注
		// uid 登录用户id
		// xid 专栏或者作者id
		$sql = "";	
		if( $type == 0 ) {	// 专栏
			switch( $action) {
				case 0:
					$date = date( 'Y-m-d H:i:s ');
					$sql = "
						INSERT INTO follow_topic( user_id, topic_id, follow_date )
						VALUES ('{$uid}', '{$xid}', '{$date}')
					";
					break;
				case 1:
					$sql = "
						DELETE FROM follow_topic 
						WHERE topic_id='{$xid}' 
							AND user_id='{$uid}'
					";
					break;
			}
		}	else if( $type == 1 ) { // 作者
			switch( $action) {
				case 0:
					$date = date( 'Y-m-d H:i:s ');
					$sql = "
						INSERT INTO follow_user( user_id, follow_target_id, follow_date )
						VALUES ('{$uid}', '{$xid}', '{$date}')
					";
					break;
				case 1:
					$sql = "
						DELETE FROM follow_user
						WHERE follow_target_id='{$xid}' AND user_id='{$uid}'
					";
					break;
			}
		} else if ($type == 2 ) {
				$sql = "
					DELETE FROM follow_user
					WHERE follow_target_id='{$uid}' AND user_id='{$xid}'
				";
		}	// 准备好了$sql 
		
		if( !empty( $sql ) ) {
			if( $this->db->query( $sql ) ) 
				return true;
		}
		return false;
	}
	
	function del_feeds( $type, $uid, $xid ) {
		// 删除feeds
		// type 0=专栏 1=作者
		if( $type == 0 ) {
			$sql = "
				DELETE FROM feeds
				WHERE user_id = '{$uid}'
					AND story_id IN (
						SELECT story_id
						FROM story
						WHERE topic_id = '{$xid}'
					)
			";
		}
		else if( $type == 1 ) {
			$sql = "
				DELETE FROM feeds
				WHERE user_id = '{$uid}'
					AND story_id IN (
						SELECT story_id
						FROM story
						WHERE user_id = '{$xid}'
					)
			";
		
		}
		
		if( $this->db->query( $sql ) ) 
			return true;
		return false;
	}
	
	
	function html_page_box( $total ) {
			?>
				<div class="page-wrap">
					<div class="page-box">
						<span id="prev-next"><a href="javascript: void(0);" id="prev-page" action="change-page" type="0"  rel="0">上一页</a><a href="javascript:void(0);"  action="change-page" type="1" id="next-page" rel="2">下一页</a></span>
						<select id="page-select">
						<?php
							for( $i = 1; $i <= $total; $i++ ) {
						?>
								<option value="<?=$i?>">第&nbsp;<?=$i?>&nbsp;页</option>
						<?php
							}
						?>
						</select>
						<script>
						$(document).ready(function() {
							var selOpt = $("#page-select");
							$("#prev-page").hide();
							var pageNum = parseInt("<?=$total?>");
							selOpt.change( function() {
								var p = $(this).val();
								
								$.ajax({
									url: "<?=HOSTURL.'/module/ajax/ajax-fetch-page.php?p='?>"+p,
									dataType: 'html', 
									beforeSend: function() {
										$('#loading').show();
									},
									complete: function() {
										$('#loading').hide();
									},
									success: function( data ) {
										if( data != "") {
											$("#bding-list-wrap").html( data );
											$('html,body').animate({
												scrollTop: 0
											}, 0);
											if( p> 1 ) {
												$("#prev-page").show();
												$("#prev-page").attr('rel', p-1);
											} else if( p == 1 ) {
												$("#prev-page").hide();
											}
											
											if( p < pageNum ) {
												$("#next-page").show();
												$("#next-page").attr('rel', p+1);
											} else if( p == pageNum ) {
												$("#next-page").hide();
											}
										}
									}
								});
							} );
						
						// 上一页 下一页
							var changeP = $("a[action='change-page']");
							$.each( changeP, function( idx, elem) {
								$(elem).click(function() {
									var type = $(elem).attr('type');
									var p = $(elem).attr( 'rel' );
									//
									$.ajax({
										url: "<?=HOSTURL.'/module/ajax/ajax-fetch-page.php?p='?>"+p,
										dataType: 'html', 
										beforeSend: function() {
											$('#loading').show();
										},
										complete: function() {
											$('#loading').hide();
										},
										success: function( data ) {
											if( data != "") {
												$("#bding-list-wrap").html( data );
												$('html,body').animate({
													scrollTop: 0
												}, 0);
												if( p> 1 ) {
													$("#prev-page").show();
													$("#prev-page").attr('rel', p-1);
												} else if( p == 1 ) {
													$("#prev-page").hide();
												}
												
												if( p < pageNum ) {
													$("#next-page").show();
													$("#next-page").attr('rel', p+1);
												} else if( p == pageNum ) {
													$("#next-page").hide();
												}
											}
										}
									});
									//
								});
							
							} );
						});
						</script>
					</div>
				</div>
			<?php
			}
			
	function html_user_stories_wrap( $page, $uid, $author_id, $type = 0) {
		$size = PAGE_SIZE;
		$start =( $page - 1 ) * $size;
		$x = $this->user_statis( $author_id, 2);
		$stories_num = $x['num'];
		$total_page = ceil( $stories_num / $size );
		if( $stories_num > 0 ) {  
	?>
		<div class="display-switcher">
			<a href="javascript:void(0);" action="changep" p="<?=$page?>" type="0" rel="<?=$author_id?>"><span class="glyphicon glyphicon-th-large" title="摘要显示"></span></a>
			<a href="javascript:void(0);" action="changep" p="<?=$page?>" type="1" rel="<?=$author_id?>"><span class="glyphicon glyphicon-th-list" title="列表显示"></span></a>
		</div>
	<?php
		}
		if( $type == 0 ) {
			$this->html_user_stories( $uid, $author_id, $start, $size );
		} else if( $type == 1 ) {
			// 列表显示
			$this->html_user_stories_hoz( $uid, $author_id, $start, $size );
		}
		if( $total_page > 1 ) {
		?>
		<div class="page-switcher">
			<?php
				if( $page > 1 ) {
			?>
					<span><a href="javascript:void(0)" action="changep" type="<?=$type?>" id="prev-page" p="<?=$page - 1?>" rel="<?=$author_id?>">上一页</a></span>
			<?php
				}
				echo "<select id='sel-user-page' rel='{$author_id}' type='{$type}'>";
				for($i = 1; $i <= $total_page; $i++) {
			?>
					<option value="<?=$i?>" <?php if($page == $i) echo "selected";?>><a href="javascript:void(0)" action="changep" type="<?=$type?>" p="<?=$i?>">第<?=$i?>页</a></option>
			
			<?php
				}
				echo "</select>";
				if( $page < $total_page ) {
			?>
					<span><a href="javascript:void(0)" action="changep" type="<?=$type?>" id="prev-page" p="<?=$page +1?>" rel="<?=$author_id?>">下一页</a></span>
			<?php
				}
			?>
		</div>
		<?php
		}
	}
		
	function html_user_story_item_hoz( $uid, $story ) {
		extract( $story );
		// print_arr( $story );
		$column_img = CVIEW_PATH.$img;
		$column_link = HOSTURL."column/?id=".$cat_id;
		$story_link = HOSTURL."home/reddit?id=".$story_id;
		$s_title = $this->Public_model->story_summary( $story_title, 15 );
		$post_date = substr( $post_date, 0 , 10 );
		$edit_link = HOSTURL."home/write?act=1&id=".$story_id;
	?>
		<li id="story-<?=$story_id?>">
			<ul class="story-item-hoz">
				<li class="img"> 
					<a  href="<?=$column_link?>" target="_blank">
					<img class="media-object" src="<?=$column_img?>" title="<?=$cat_name?>" width="30px" height="30px">
					</a>
				</li>
				<li class="post-date"><?=$post_date?></li>
				<li class="story-title"><a href="<?=$story_link ?>" target="_blank" action="eat-bding" rel="<?=$story_id?>" title="<?=$story_title?>"><?=$s_title?></a></li>
				<?php
					if( ($uid != -1) && ($uid == $user_id ) ) {
				?>
				<li class="op">
					<span><a href="<?=$edit_link?>"><i class="glyphicon glyphicon-edit" style="margin-right: 5px;"></i>编辑</a></span>&nbsp;&nbsp;
					<span><a href="javascript:void(0);" action="del-bding" rel="<?=$story_id?>"><i class="glyphicon glyphicon-remove-sign" style="margin-right: 5px;"></i>删除</a></span>
				</li>
				<?php
					}
				?>
				<li class="view-count pull-right"><i class="glyphicon glyphicon-eye-open" style="margin-right: 5px;"></i><?=$view_count?></li>
				
			</ul>
			
		</li>
	<?php
	}
		
		
		function get_author_followers( $author_id, $start, $size ) {
		$sql = "
			SELECT
				user.user_id,
				user.user_nickname,
				user.user_photo
			FROM user, follow_user
			WHERE
				follow_user.follow_target_id = '{$author_id}'
				AND follow_user.user_id = user.user_id
			ORDER BY follow_user.follow_date DESC
			LIMIT {$start}, {$size}
		";
		
		$query = $this->db->query( $sql );
		return $query->result_array();
	}
	
	function	html_author_followers( $author_id, $start, $size ) {
		$x = $this->user_statis($author_id, 2);
		$stories_num = $x['num'];
		$data = $this->get_author_followers( $author_id, $start, $size );
		$more_link = HOSTURL."user/follow?type=2&id={$author_id}";
		if( count( $data ) > 0 ) {
		?>
			<div class="attach-wrap">
				<div class="title"><span>谁关注了 Ta<i style="color: #00664D">/ who follow Ta</i></span></title></div>
				<div class="attach-box">
				<ul>
				<?php
					// print_arr( $data );
					foreach( $data as $item ) {
						extract( $item );
						$user_link = HOSTURL."user/?id=".$user_id;
						$user_photo = UVIEW_PATH.$user_photo
				?>
						<li class="follow-item"><a href="<?=$user_link?>" target="_blank" title="<?=$user_nickname?>" alt="<?=$user_nickname?>"><img src="<?=$user_photo?>" width="50px" height="50px" class="img-rounded"/></a></li>
				<?php
					}
				?>
				</ul>
				<?php
				if( $stories_num > $size ) {
				?>
				<p class="more"><a href="<?=$more_link?>">全部</a></p>
				<?php
				}
				?>
				</div>
			</div>
		<?php
		}
	}
	
	
	
	function html_profile_editor( $data = array() ) {
		extract( $data );
		$year = substr( $birthday, 0, 4 );
		$month = substr( $birthday, 5, 2 );
		$day = substr( $birthday, 8, 2 );
	
	?>
	<div class="profile-wrap">
		<div class="profile-box">
			<form action="<?=HOSTURL.'user/chkprof'?>" method="post" class="form-horizontal" role="form" id="profile-form">
				<div class="form-grounp">
					<div id="error-place">
						<?php echo validation_errors();?>
					</div>
				</div>
				  <div class="form-group">
					<label for="nickname" class="col-sm-2 control-label">名号</label>
					<div class="col-sm-6">
					  <input type="text" name="nickname" class="form-control input-sm inp-txt"  value="<?=$user_nickname?>" autocomplete="off" />
					</div>
				  </div>
				  
				  <div class="form-group gender">
					<label for="gender" class="col-sm-2 control-label">性别</label>
					<div class="col-sm-8">
						<label class="radio-inline">
							<input type="radio" name="gender" value="1" <? if( $gender == 1 ) echo "checked='checked'";?> />男
						</label>
						<label class="radio-inline">
							<input type="radio" name="gender" value="2" <? if( $gender == 2 ) echo "checked='checked'";?> />女
						</label>
						<label class="radio-inline">
							<input type="radio" name="gender" value="0" <? if( $gender == 0) echo "checked='checked'";?> />保密
						</label>
					</div>
				  </div>
				  
				  <div class="form-group">
					<label for="birthday" class="col-sm-2 control-label">生日</label>
					<div class="col-sm-8">
					<?php $this->html_birthday_select( $year, $month, $day );?>
					</div>
				  </div>
				  
				  <div class="form-group">
					<label for="location" class="col-sm-2 control-label">所在地</label>
					<div class="col-sm-8">
						<input type="text" name="province" class="form-control input-sm inp-location" value="<?=$province?>" autocomplete="off" />省
						<input type="text" name="city"  class="form-control input-sm inp-location"  value="<?=$city?>" autocomplete="off" />市
					</div>
				  </div>
				  
				  <div class="form-group">
					<label for="gra_school" class="col-sm-2 control-label">毕业学校</label>
					<div class="col-sm-8">
					  <input type="text" name="gra_school" class="form-control input-sm inp-txt" value="<?=$gra_school?>" autocomplete="off" />
					</div>
				  </div>
				  
				  <div class="form-group">
					<label for="workplace" class="col-sm-2 control-label">工作单位</label>
					<div class="col-sm-8">
					  <input type="text" name="workplace" class="form-control input-sm inp-txt"  value="<?=$workplace?>" autocomplete="off" />
					</div>
				  </div>
				  
				  <div class="form-group">
					<label for="intro" class="col-sm-2 control-label">自我简介</label>
					<div class="col-sm-8">
						<textarea class="form-control"  name="intro" rows="3"><?=$user_desc?></textarea>
					</div>
				  </div>
				  
				  
				  <div class="form-group">
					<div class="col-sm-offset-2 col-sm-8">
					 <input type="hidden" name="uid" value="<?=$user_id?>"/><br/>
					  <button type="submit" class="btn btn-primary btn-sm pull-right">完成修改</button>
					</div>
				  </div>
				</form>
		</div>
	</div>
	<?php
	}
	
	function html_photo_editor( $login=array() ) {
		extract( $login );
		$user_photo = UVIEW_PATH.$user_photo;
		$attrs = array(
			'method' =>'post', 
			'class'=>"form-inline",
			'enctype'=>"multipart/form-data" 
			
		);
		$act =base_url().'user/do_upload';
	?>
		<div class="peditor-wrap">
			<div class="peditor-box">
				<h3><?=$user_nickname?>的当前头像:</h3>
				<div>
					<img src="<?=$user_photo?>" width="200px" height="200px"/>
				</div>
			</div>
			
			<div class="upload-box">
				<?=form_open($act, $attrs); ?>
			  <div class="form-group">
				<label class="sr-only" for="photo">修改头像</label>
				<input type="file" name="photo" size="30" />
			  </div>
				<input type="submit" class="btn btn-primary btn-sm" name="upload_btn" value="上传" placeholder="Enter email"/>
			
			</form>
			</div>
		</div>
	<?php
	}
	
	function html_password_editor( $data=array() ) {
		extract( $data );
		// print_arr( $data );	//tbd
		$act = base_url()."user/chkpass";
	?>
		<div class="pass-wrap">
			<div class="pass-box">
				<form class="form-horizontal" action="<?=HOSTURL.'user/chkpass'?>" method="post" action="<?=$act?>" id="chk-pass-form" role="form">
					<div class="form-group">
						<div id="error-place">
							<?=validation_errors();?>
						</div>
					</div>
				  <div class="form-group">
					<label for="password" class="col-sm-2 control-label">原密码</label>
					<div class="col-sm-8">
					  <input type="password" name="old_pass" class="form-control input-sm inp-txt"  autocomplete="off" />
					</div>
				  </div>
				  
				  <div class="form-group">
					<label for="password" class="col-sm-2 control-label">新密码</label>
					<div class="col-sm-8">
					  <input type="password" id="new_pass" name="new_pass" class="form-control input-sm inp-txt" autocomplete="off" />
					</div>
				  </div>
				  
				  <div class="form-group">
					<label for="password" class="col-sm-2 control-label">确认新密码</label>
					<div class="col-sm-8">
					  <input type="password" name="new_pass2" class="form-control input-sm inp-txt"  autocomplete="off" />
					</div>
				  </div>
				  
				  
				  <div class="form-group">
					<div class="col-sm-offset-2 col-sm-10">
					 <input type="hidden" name="uid" value="<?=$user_id?>"/><br/>
					  <button type="submit" class="btn btn-primary btn-sm pull-left">完成修改</button>
					</div>
				  </div>
				</form>
				
			</div>
		</div>
	<?php
	}
	
	function html_birthday_select( $birth_year, $birth_month, $birth_day ) {
	?>
		<select name="year" class="form-control input-sm inp-birth">
		<?php
			$toyear = date( 'Y' );
			for($from = 1900; $from <= $toyear; $from++) {
				if ($from == $birth_year) {
					echo "<option value='{$from}' selected>$from</option>"; 
				} else {
					echo "<option value='{$from}'>$from</option>";
				}
			}
		?>
	</select>年
							
		<select name="month" class="form-control input-sm inp-birth">
			<?php
				for($month = 1; $month <= 12; $month++) {
					if($month == $birth_month) {
						echo "<option value='{$month}' selected>$month</option>";
					}	else {
						echo "<option value='{$month}'>$month</option>";
					}
				}
			?>
		</select>月
		
		<select name="day" class="form-control input-sm inp-birth">
			<?php
				for($day = 1; $day <= 31; $day++) {
					if($day == $birth_day) {
						echo "<option value='{$day}' selected>$day</option>";
					}	else {
						echo "<option value='{$day}'>$day</option>";
					}
					
				}
			?>
		</select>日
	<?php
	}
	
	function html_follow_list( $data=array() ) {
		extract( $data );
	?>
		<div class="follow-wrap">
			<div class="follow-box">
			<?php
				$num = count( $list );	// 统计数
				$num = ' ('.$num.')';
				if( count( $list ) == 0 ) {
					echo "<p>尚未关注</p>";
				} else {
					$title = $title.$num;
			?>
				<h3><?=$title?></h3>
			<?php
					foreach( $list as $item ) {
						$this->html_follow_list_item( $uid, $xid, $type, $item );
					}
				}
				if( $uid == $xid ) {	// 如果当前查看的作者与登录用户相同，则加载script
				?>
				<script>
				$( function() {
					var cancelFollows = $("a[action='cancel-follow']");
					$.each( cancelFollows, function( idx, elem ) {
						
						$(elem).click( function() {
							var type = $( elem) .attr( 'type' );
							var id = $( elem ).attr( 'rel' );
							// $("#follow-item-" + id ).remove();
							// alert( type );
							$.ajax( {
								url: "<?=base_url()?>ajax/follow?action=1&type="+type+"&id="+id,
								success: function( data ) {
									// alert( data );
									$("#follow-item-" + id ).remove();
								},
								beforeSend: function() {
									$('#loading').show();
								},
								complete: function() {
									$('#loading').hide();
								}
								
							} );
						} );
						
						
					} );
				} );
				</script>
				<?php
				}
			?>
			</div>	
		</div>
		<?php
	}
	
	function html_follow_list_item( $uid , $xid, $type, $data = array() ) {
		// html每一条follow信息
		// type 0=专栏 1=作者 2=粉丝
		extract( $data );
		$msg_link = HOSTURL."user/write_msg?type=1&id=".$id;
		if( $type == 0 ) {
			$img = CVIEW_PATH.$img;
			$link = HOSTURL.'column?id='.$id;
		} else if( $type == 1 || $type == 2 )  {
			$img = UVIEW_PATH.$img;
			$link = HOSTURL.'user?id='.$id;
		}
		$short = "";
		if( $uid != $xid ) $short = " follow-short";
		if( $type == 0 || $type == 1 ) {
			$action = "取消关注";
		} else if( $type == 2 ) {
			$action = "移除读者";
		}
		
		$both = "&nbsp;";
		$follow_flag = 0;
		if( $type == 1 ) {
			$follow_flag = $this->follow_or_not( 1, $id, $xid ) ;
		} else if( $type == 2 ) {
			$follow_flag = $this->follow_or_not( 1, $xid, $id );
		}
		if( $uid == $xid && $follow_flag == 1 ) $both = "[互相关注]";
	?>
		<div class="follow-item"  id="follow-item-<?=$id?>">
			<div class="thumbnail<?=$short?>">
			<div class="img-wrap">
				<a href="<?=$link?>" target="_blank"><img src="<?=$img?>" width="80px" height="80px" ></a>
			  </div>
			 <div class="caption">
				<h3><a href="<?=$link?>" target="_blank"><?=$name?></a><?php if( $type == 1 || $type == 2 ) {?>&nbsp;<a href="<?=$msg_link?>" title="写信" class="send-msg"><span class="glyphicon glyphicon-send"></span></a><?php }?></h3>
				<p class="both"><?=$both?></p>
			</div>
				<?php
					if( $uid == $xid ) {
					?>
					<div class="user-action">
						<a href="javascript:void(0);" class="btn btn-warning btn-xs" action="cancel-follow" type= "<?=$type?>" rel="<?=$id?>"><?=$action?></a>	
					</div>
					<?php
					}
					?>
		  </div>
		
	</div>
	<?php
	}
	
	function get_msg_list( $uid, $type, $start, $size ) {
		$sql = "";
		switch( $type ) {
			case 0: 
			case 1:
					$sql = "
						SELECT
							user.user_id,
							user.user_nickname,
							user.user_photo,
							mail.content,
							mail.status,
							mail.sent_date AS date,
							mail.mail_id,
							mail.type
						FROM mail, user
						WHERE
							mail.receiver = '{$uid}'
							AND mail.sender = user.user_id
							AND mail.type = '{$type}'
						ORDER BY mail.sent_date DESC
						LIMIT {$start}, {$size}
					";
				break;
			
			case 2:
				$sql = "
						SELECT
							user.user_id,
							user.user_nickname,
							user.user_photo,
							mail.content,
							mail.status,
							mail.sent_date AS date,
							mail.mail_id
						FROM mail, user
						WHERE
							mail.sender = '{$uid}'
							AND mail.receiver = user.user_id
						ORDER BY mail.sent_date DESC
						LIMIT {$start}, {$size}
					";
			
				break;
		}
	
		
		$query = $this->db->query( $sql );
		return $query->result_array();
		
	}
	
	function html_msgbox( $page, $uid, $type ) {
		$size = MSG_SIZE;
		$start = ( $page - 1 ) * $size;
		
		$data = $this->get_msg_list( $uid, $type, $start, $size );
		$tcls = "";
		$tcls1 = "";
		$link0 = HOSTURL."user/msg?type=0";
		$link1 = HOSTURL."user/msg?type=1";
		if( $type == 0 ) {
			$no_msg = "没有收到私信。";
			$tcls = "class='active'";
		} else if( $type == 1 ) {
			$no_msg = "没有收到通知。";
			$tcls1 = "class='active'";
		} else if( $type == 2 ) {
			$no_msg = "没有发送信件。";
		}
	?>
		<div class="msgbox-wrap">
			<div class="msgbox">
				<div class="msg-list">
					<?php
					if( count( $data ) == 0 ) {
						echo "<p>{$no_msg}</p>";
					} else {
					?>
					<ul>
						<?php
							foreach( $data as $item ) {
								extract( $item );
								$user_photo = UVIEW_PATH.$user_photo;
								$uname = $this->Public_model->content_summary( $user_nickname, 4 );
								$s_content = $this->Public_model->content_summary( $content, 10 );
								$s_content .= "...";
								$user_link = HOSTURL."user/?id=".$user_id;
								$date = substr( $date, 0 , 16 );
								
								if( $status == 0 ) {
									$s = "未读";
									$not_read_cls = "bold";
								} else if( $status == 1 ) {
									$s = "已读";
									$not_read_cls = "";
								}
								$sender_link = HOSTURL."user/?id={$user_id}";
						?>
						<li  id="msg-<?=$mail_id?>" class="<?=$not_read_cls?>">
							<ul class="msg-item">
							<li class="avatar">
								<a href="<?=$sender_link?>" target="_blank"><img src="<?=$user_photo?>" width="30px" height="30px"/></a>
							</li>
							<li class="date"><?=$date?></li>
							<li class="name">
								<a href="<?=$user_link?>" target="_blank" title="<?=$user_nickname?>"><?=$uname?></a>
							</li>
							<li class="short-content">
								<?=$s_content?>
							</li>
							<li class="check"><a href='javascript:void(0);' class='msg-link' action='read-msg' rel='<?=$mail_id?>' type='<?=$type?>' status="<?=$status?>">查看&nbsp;<i class="glyphicon glyphicon-chevron-down"></i></a></li>
							<li class="check"><a href='javascript:void(0);' class='msg-link' action='del-msg' rel='<?=$mail_id?>' type='<?=$type?>'>删除&nbsp;<i class="glyphicon glyphicon-remove"></i></a></li>
							<li class="status" id="msg-status-<?=$mail_id?>"><?=$s?></li>
							</ul>
							<div id="reply-msg-<?=$mail_id?>" class="reply-msg-wrap">
								<div class="reply-msg-box">
								  <div class="content"<p><?=$content?></p></div>
								  <?php
								  if( $type == 0 ) {
									$reply_link =  HOSTURL."user/write_msg?type=1&id={$user_id}";
								  ?>
								  <p><a href="<?=$reply_link?>" target="_blank" class="btn btn-primary btn-sm" role="button">回信</a></p>
								  <?php
								  }
								  ?>
								</div>
							</div>
						</li>
						<?php
						}
						?>
					</ul>
					<?php
					}
					?>
				</div>
			</div>
		</div>
	<?
	}
	
	function html_write_msg($receiver, $sender, $type) {
		if( $type == 1 ) {
			$recv_id = $receiver['user_id'];
			$recv_photo = UVIEW_PATH.$receiver['user_photo'];
			$recv_name = $receiver['user_nickname'];
			$recv_link = HOSTURL."user/?id=".$recv_id;
		}
		
		$sender_id = $sender['user_id'];
		$sender_photo = UVIEW_PATH.$sender['user_photo'];
		$sender_name = $sender['user_nickname'];
		$sender_link = HOSTURL."user/?id=".$sender_id;
		
		$date = date('Y-m-d');
		$act = base_url()."user/chkmsg"
	?>
		<div class="write-msg-wrap">
			<div class="write-msg-box" id="show-msg-status">
				<h3 class="glyphicon glyphicon-send">&nbsp;写给<?=$recv_name?>的信：</h3>
				
				<div class="msg-bd">
					<form class="form-horizontal" role="form" id="send-msg-form" method="post" action="<?=$act?>">
						<ul>
							<li>
								<div id="error-place">
									<?php echo validation_errors(); ?>
								</div>
							</li>
							<?php
							if( $type == 1 ) {
							?>
							<li class="receiver" id="receiver">
								<span class="pull-right photo"><a href="<?=$recv_link?>" target="_blank" title="<?=$recv_name?>" id="recv_photo"><img src="<?=$recv_photo?>" width="40px" height="40px" /></a></span>
								<span class="pull-left"><a href="<?=$recv_link?>" target="_blank" id="recv_name"><?=$recv_name?></a>：</span>
							</li>
							<?php
							} 
							?>
							<li><textarea class="form-control" rows="8" name="content"></textarea></li>
							<li class="sender">
								<span class="pull-right"><a href="<?=$sender_link?>" target="_blank"><?=$sender_name?></a></span>
							</li>
							<li	class="date">
								<span class="pull-right"><?=$date?></span>
							</li>
							<li>
								<?php
								if( $type == 1 ) {
								?>
								<input type="hidden" name="receiver" value="<?=$recv_id?>"/>
								<?php
								}
								?>
								<input type="hidden" name="sender" value="<?=$sender_id?>"/>
							</li>
						</ul>
						<button class="btn btn-primary btn-sm" type="submit" name="btn_send">发&nbsp;&nbsp;送</button>
					</form>
				</div>
			</div>
		</div>
	<?php
	}
	
	function get_author_comments( $page, $author_id ) {
		$size = COMMENT_SIZE;
		$start = ( $page - 1 ) * $size;
		
		$sql = "
			SELECT
				story.story_id,
				story.story_title,
				story.user_id AS writer_id, 
				author.user_nickname AS writer_name,
				reader.user_id AS reader_id,
				reader.user_nickname AS reader_name,
				reader.user_photo AS reader_photo,
				comment.comment_id,
				comment.comment_date,
				comment.comment_content,
				comment.talk_with_id
			FROM story, user AS author, user AS reader, comment
			WHERE 
				comment.user_id = reader.user_id
				AND story.story_id = comment.story_id 
				AND story.user_id = author.user_id
				AND ( 
					story.user_id = '{$author_id}'
					OR comment.user_id = '{$author_id}'
				)
			ORDER BY
				comment.comment_date DESC
			LIMIT {$start}, {$size}
		";
		
		$query = $this->db->query( $sql );
		return $query->result_array();
	}
	
	function html_author_comments_wrap($page, $uid, $author_id ) {
		$data = $this->get_author_comments($page, $author_id);
	?>
		<div class="user-comments-wrap">
			<div class="comment-list">
				
				<?php
				if( count( $data ) == 0 ) {
					echo "<p>没有与作者相关的评论。</p>";
				} else if( count( $data ) > 0 ) {
					foreach( $data as $item ) {
						// print_arr( $item );	// tbd
						extract( $item );
						// print_arr( $item );
						
						$story_link = HOSTURL."home/reddit?id={$story_id}";
						$writer_link = HOSTURL."user/?id={$writer_id}";
						$reader_link = HOSTURL."user/?id={$reader_id}";
						$reader_photo = UVIEW_PATH.$reader_photo;
			
						$r_name = $this->Public_model->content_summary( $reader_name, 4 );
						$a_name = $this->Public_model->content_summary( $writer_name, 4 );
						$s_title = $this->Public_model->content_summary( $story_title, 20 );
						$comment_date = substr( $comment_date, 0, 16 );
						
						$r_name = "<a href='{$reader_link}' target='_blank' title='{$reader_name}'>".$r_name."</a>";
						$a_name = "<a href='{$writer_link}' target='_blank' title='{$writer_name}'>".$a_name."</a>";
						
						if( $reader_id == $author_id ) {
							$r_name = "作者";
							if( $writer_id == $author_id ) {
								$a_name = "自己";
							}
						} elseif ( $writer_id == $author_id ) {
							$a_name = "作者";
						}
						?>
						
					<div class="comment-item">
						<div class="photo">
							<a href="<?=$reader_link?>" target="_blank"><img src="<?=$reader_photo?>"  title="<?=$reader_name?>"  width="25px" height="25px"/></a>
						</div>
						
						<div class="content">
							<div class="record pull-right">
								<ul>
									<li class="date"><?=$comment_date?></li>
									<li class="name" style="width: 300px;"><?=$r_name?>评论了<?=$a_name?>的：<a href="<?=$story_link?>" target="_blank" title="<?=$story_title?>" action="eat-bding" rel="<?=$story_id?>"><?=$s_title?></a></li>
								</ul>
								
							</div>
							
							<div class="say-words">
								<p><?=$comment_content?></p>
							</div>
							
							<div class="act pull-right">
								<?php
								$this->Story_model->html_comment_interact( $comment_id, $story_id, $uid, -1);
								?>
							</div>
						</div>
					</div>
					
					<?php
					}
				}
				?>
			
			</div>
			<script>
			var voteCommentBtns = $("a[action='vote-comment']");
			$.each( voteCommentBtns, function(idx, elem) {
				$(elem).click( function() {
					var commentId = $(elem).attr("rel");
					var voted = $(elem).attr("voted");
					// alert( voted );
					$.ajax({
						url: "<?=base_url()?>ajax/vote_comment?comment_id="+commentId+"&voted="+voted,
						dataType: 'json',
						success: function( data ) {
							if( data.status == 1 ) {
								if( voted == 1 ) {
									$(elem).removeClass("voted");
									$(elem).attr( 'voted', 0 );
									$("#comment-vote-"+commentId).text( data.vote_num );
								} else if( voted == 0 ) {
									$(elem).addClass("voted");
									$(elem).attr( 'voted', 1 );
									$("#comment-vote-"+commentId).text( data.vote_num );
								}
							}
						}
					});
				} );
			});
		</script>
		</div>
	<?php
	}
	
	function get_author_votes( $page, $author_id, $vote_for = 0 ) {
		$size = COMMENT_SIZE;
		$start = ( $page - 1 ) * $size;
		
		$sql = "
			SELECT
				story.story_id,
				story.story_title,
				story.user_id AS writer_id, 
				author.user_nickname AS writer_name,
				reader.user_id AS reader_id,
				reader.user_nickname AS reader_name,
				reader.user_photo AS reader_photo,
				vote.vote_date
			FROM story, user AS author, user AS reader, vote
			WHERE 
				vote.user_id = reader.user_id
				AND story.story_id = vote.story_id 
				AND story.user_id = author.user_id
				AND vote.vote_for='{$vote_for}'
				AND vote.vote_type = '1'
				AND ( 
					story.user_id = '{$author_id}'
					OR vote.user_id = '{$author_id}'
				)
			ORDER BY
				vote.vote_date DESC
			LIMIT {$start}, {$size}
		";
		
		$query = $this->db->query( $sql );
		return $query->result_array();
	}
	
	
	
	function html_author_votes_wrap($page, $uid, $author_id ) {
		$data = $this->get_author_votes($page, $author_id);
	?>
		<div class="user-comments-wrap">
			<div class="comment-list">
				
				<?php
				if( count( $data ) == 0 ) {
					echo "<p>没有与作者相关的投票信息。</p>";
				} else if( count( $data ) > 0 ) {
					foreach( $data as $item ) {
						extract( $item );
						$story_link = HOSTURL."home/reddit?id={$story_id}";
						$writer_link = HOSTURL."user/?id={$writer_id}";
						$reader_link = HOSTURL."user/?id={$reader_id}";
						$reader_photo = UVIEW_PATH.$reader_photo;
			
						$r_name = $this->Public_model->content_summary( $reader_name, 4 );
						$a_name = $this->Public_model->content_summary( $writer_name, 4 );
						$s_title = $this->Public_model->content_summary( $story_title, 20 );
						$vote_date = substr( $vote_date, 0, 16 );
						
						$r_name = "<a href='{$reader_link}' target='_blank' title='{$reader_name}'>".$r_name."</a>";
						$a_name = "<a href='{$writer_link}' target='_blank' title='{$writer_name}'>".$a_name."</a>";
						
						if( $reader_id == $author_id ) {
							$r_name = "作者";
							if( $writer_id == $author_id ) {
								$a_name = "自己";
							}
						} elseif ( $writer_id == $author_id ) {
							$a_name = "作者";
						}
						
						?>
					<div class="vote-item comment-item">
							<div class="photo">
								<a href="<?=$reader_link?>" target="_blank"><img src="<?=$reader_photo?>"  title="<?=$reader_name?>"  width="25px" height="25px"/></a>
							</div>
							
							<div class="content">
								<div class="record">
									<ul>
										<li class="date"><?=$vote_date?></li>
										<li class="name"><?=$r_name?>赞了<?=$a_name?>的：<a href="<?=$story_link?>" target="_blank" title="<?=$story_title?>" action="eat-bding" rel="<?=$story_id?>"><?=$s_title?></a></li>
									</ul>
									
								</div>
							</div>
					</div>
						<?php
					}
				}
				?>
			
			</div>
		</div>
	<?php
	}
	
	function send_msg( $data, $type ) {
		extract( $data );
		$sent_date = date('Y-m-d H:i:s');
		$sql = "
			INSERT INTO
				mail( sender, receiver, content, sent_date, type) 
			VALUES
				( '{$sender}', '{$receiver}', '{$content}', '{$sent_date}', '{$type}') 
		";
		
		$this->db->query( $sql );
	}
	
	function check_login($user_email, $user_pass) {
		$user_email = mysql_real_escape_string( $user_email );
		$user_pass= mysql_real_escape_string( $user_pass );
		$sql = "
			SELECT COUNT(*) AS ok
			FROM user
			WHERE user_email = '{$user_email}'
		";
		
		$query = $this->db->query( $sql );
		$ok = $query->row()->ok;
		if( $ok == 1 ) {
			$user_pass = md5( $user_pass );
			$sql = "
				SELECT COUNT(*) AS ok
				FROM user
				WHERE user_email = '{$user_email}'
					AND user_pass = '{$user_pass}'
			";
			$query = $this->db->query( $sql );
			$ok = $query->row()->ok;
			if( $ok ) {
				return 0;
			} else {
				return 2;	// 密码不正确
			}
		} else {
			return 1; // 邮箱不存在
		}
		
	}
	
	function query_uid( $user_email ) {
		$user_email = mysql_real_escape_string( trim( $user_email ) );
		$sql = "
			SELECT user_id 
			FROM user
			WHERE user_email = '{$user_email}'
		";
		$query = $this->db->query( $sql );
		return $query->row()->user_id;
	}
	
	
	function get_user_drafts( $page, $author_id ) {
		$size = 100;
		$start = ( $page - 1 ) * $size;
		$sql = "
			SELECT 
				topic.topic_id AS cat_id,
				topic.topic_title AS cat_name,
				topic.topic_icon AS img,
				user.user_id,
				user.user_nickname,
				story.story_id,
				story.story_title,
				story.story_content,
				story.post_date,
				story.view_count
			FROM story,topic,user
			WHERE story.user_id = '{$author_id}' 
			  AND story.topic_id=topic.topic_id
			  AND story.user_id = user.user_id
			  AND story.story_type = '1'
			ORDER BY story.post_date DESC
			LIMIT {$start}, {$size}
		";
		$query = $this->db->query( $sql );
		return $query->result_array();
	}
	
	function html_author_drafts_wrap( $page , $uid, $author_id ) {
		// echo "";
		$data = $this->get_user_drafts( $page, $author_id );
		?>
		<div class='column-bdings-wrap' id='bding-feed-list'>
				<div class='column-bdings-box'>
			<?php
			if( count( $data ) == 0 ) {
				echo "<p>没有日记</p>";
			} else {
				foreach( $data as $item ) {
					$this->Public_model->html_bding_item_column($uid, $item );
				}
			}
			?>
				</div>
		</div>
		<script src="<?=base_url().'comm/js/user-action.js'?>"></script>
		<?php
	}
	
	function check_msg_ok( $msg_id, $uid ) {
		$sql = "
			SELECT COUNT(*) AS ok
			FROM mail
			WHERE
				mail_id = '{$msg_id}'
				AND ( 
					receiver = '{$uid}'
					OR sender='{$uid}'
				)
		";
		$query = $this->db->query( $sql );
		return $query->row()->ok;
	}
	
	function del_msg( $msg_id, $uid ) {
		$ok = $this->check_msg_ok( $msg_id, $uid );
		if( $ok == 1 ) {
			$sql = "
				DELETE
				FROM mail
				WHERE mail_id = '{$msg_id}'
			";
			if( $this->db->query( $sql ) ) {
				return 1;
			}
			
		}
		return 0;
	}
	
	function read_msg( $type, $msg_id, $uid ) {
		if( $type == 0 || $type == 1 ) {
			$ok = $this->check_msg_ok( $msg_id, $uid );
			if( $ok == 1 ) {
				$sql = "
					UPDATE mail
					SET status = '1'
					WHERE mail_id = '{$msg_id}'
				";
				if( $this->db->query( $sql ) ) {
					return 1;
				}
			}
		}
		return 0;
	}
	
	function num_msg( $recv_id, $type ) {
		$sql = "
			SELECT COUNT(*) AS num
			FROM mail
			WHERE receiver = '{$recv_id}'
				AND type='{$type}'
				AND status = '0'
		";
		$query = $this->db->query( $sql );
		return $query->row()->num;
	}
	
	function html_user_photo( $a = array() ) {
		extract( $a );
		$user_photo = UVIEW_PATH.$user_photo;
		$num1 = $this->User_model->num_msg( $user_id, 0);
		$num2 = $this->User_model->num_msg( $user_id, 1 );
		$num = $num1 + $num2;

	?>
	<div class="primary-item user-photo dropdown pull-right">
		<a href="<?=HOSTURL.'user'?>" data-toggle="dropdown" class="dropdown-toggle" title="<?=$user_nickname?>" target="_blank">
			
			<img src="<?=$user_photo?>" width="40px" height="40px" class="img-circle"/>
			<?php
			if( $num > 0 ) {
			?>
			<span class="badge"><?=$num?></span>
			<?php
			}
			?>
		</a>
		<ul class="dropdown-menu" role="menu">
			<li><a href="<?=HOSTURL.'user'?>">个人主页</a></li>
			<li><a href="<?=HOSTURL.'user/editp?type=1'?>">修改头像</a></li>
			<li class="divider"></li>
			<li><a href="<?=HOSTURL.'user/msg?type=0'?>">私信
				<?php
				if( $num1 > 0 ) {
				?>
				<span class="badge pull-right"><?=$num1?></span>
				<?php
				}
				?>
				</a>
			</li>
			<li><a href="<?=HOSTURL.'user/msg?type=1'?>">通知
				<?php
				if( $num2 > 0 ) {
				?>
				<span class="badge pull-right"><?=$num2?></span>
				<?php
				}
				?>
			</a></li>
			
			<li class="divider"></li>
			<li><a href="<?=HOSTURL.'user/logout'?>">退出</a></li>
		</ul>
	</div>
	<?php
	}
	
	function check_register( $data ) {
		extract( $data );
		$user_pass = mysql_real_escape_string( trim( $user_pass ) ); 
		$confirm_user_pass = mysql_real_escape_string( trim( $confirm_user_pass ) ); 
		if( $user_pass != $confirm_user_pass ) return 1;	// 两次密码不一致
		
		$user_email = mysql_real_escape_string( trim( $user_email ) ); 
		$sql = "
			SELECT COUNT(*) AS ok
			FROM user
			WHERE user_email = '{$user_email}'
		";
		$query = $this->db->query( $sql );
		$ok = $query->row()->ok;
		if( $ok == 1 ) 
			return 2;	//已注册
		
		$user_pass = md5( $user_pass );	// 
		$gender = isset( $_POST['gender'] ) ? $_POST['gender'] : 0;
		$year = isset( $_POST['year'] ) ? $_POST['year'] : "";
		$month = isset( $_POST['month'] ) ? $_POST['month'] : "";
		$day = isset( $_POST['day'] ) ? $_POST['day'] : "";
		$birthday = $year.'-'.$month.'-'.$day;
		$birthday = mysql_real_escape_string( trim( $birthday ) ); 
		$province = mysql_real_escape_string( trim( $province ) ); 
		$city = mysql_real_escape_string( trim( $city ) ); 
		$graduate = mysql_real_escape_string( trim( $graduate ) ); 
		$workplace = mysql_real_escape_string( trim( $workplace ) ); 
		$user_nickname = mysql_real_escape_string( trim( $user_nickname ) ); 
		$reg_date = date( 'Y-m-d H:i:s');
		$last_login_date = $reg_date;
		
		$sql = "
			INSERT INTO
				user( 
					user_email, 
					user_pass, 
					province, 
					city, 
					gra_school, 
					workplace, 
					birthday, 
					user_nickname, 
					user_reg_date, 
					last_login_date,
					gender
				)
			VALUES
				(
					'{$user_email}',
					'{$user_pass}',
					'{$province}',
					'{$city}',
					'{$graduate}',
					'{$workplace}', 
					'{$birthday}', 
					'{$user_nickname}', 
					'{$reg_date}', 
					'{$last_login_date}',
					'{$gender}'
				)
		";
		if( $this->db->query( $sql ) ) {
			return 0;
		} else {
			return 3;
		}
		
	}
	
}
?>